<?php

namespace App\Http\Controllers\CRM;

use App\Helper\ApiResponseHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\CRM\MemberRequest;
use App\Http\Resources\CRM\MemberResource;
use App\Models\Member;
use Illuminate\Http\Request;

class MemberController extends Controller
{
    public function getList(Request $request)
    {
        $query = Member::latest();

        if (!empty($request->phone))
            $query->where('phone', 'like', '%' . $request->phone . '%');

        return MemberResource::collection($query->paginate());
    }

    public function getInfo(Member $member)
    {
        return new MemberResource($member);
    }

    public function create(MemberRequest $request)
    {
        if (Member::withPhone($request->phone)->exists())
            return ApiResponseHelper::json([], 400, '手机号已存在');

        $member = Member::create($request->only([
            'name', 'phone', 'sex'
        ]));
        $member->refresh();

        return new MemberResource($member);
    }

    public function edit(Member $member, MemberRequest $request)
    {
        if (Member::withPhone($request->phone)->where('id', '!=', $member->id)->exists())
            return ApiResponseHelper::json([], 400, '手机号已存在');

        $member->update($request->only(['name', 'phone', 'sex']));

        return new MemberResource($member);
    }
}
